/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

public abstract class HttpClientRequestRunner<M extends HttpRequestBase, T> {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    private final LogLines logLines;

    public HttpClientRequestRunner(LogLines logLines) {
        this.logLines = logLines;
    }

    protected abstract M getHttpRequest(URI uri) throws Exception;

    protected abstract T onSuccess(HttpResponse response, LogLines logLines) throws Exception;

    protected abstract void onFailure(HttpResponse response, LogLines logLines) throws Exception;

    protected boolean isFailure(HttpResponse response) throws Exception {
        return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    }

    protected String getResponseContentAsString(HttpResponse response) throws Exception {
        return IOUtils.toString(response.getEntity().getContent()).trim();
    }

    public T run(URI uri) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();

        try {
            M httpRequest = getHttpRequest(uri);

            if (logLines != null) {
                logLines.log(httpRequest.getRequestLine().toString());
            }

            HttpResponse response = httpclient.execute(httpRequest);
            HttpEntity resEntity = response.getEntity();

            if (logLines != null) {
                logLines.log("Response status line: " + response.getStatusLine().toString());
                if (resEntity != null) {
                    logLines.log("Response content length: " + resEntity.getContentLength());
                }
            }

            T result = null;

            if (isFailure(response)) {
                result = onSuccess(response, logLines);
            } else {
                onFailure(response, logLines);
            }

            EntityUtils.consume(resEntity);

            return result;
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}
